package com.wyzz.hr.bo.impl;

import com.wyzz.hr.bo.IEmpsalarydatadefBo;
import com.wyzz.hr.bo.IIodefBo;
import com.wyzz.hr.bo.IOutmatchBO;
import com.wyzz.hr.bo.IOutmatchBasicBO;
import com.wyzz.hr.bo.IOutmatchModelBO;
import com.wyzz.hr.dao.IEmpsalarydatadefDao;
import com.wyzz.hr.pojo.Empsalarydatadef;
import com.wyzz.hr.pojo.Iodef;
import com.wyzz.hr.pojo.Outmatch;
import com.wyzz.hr.pojo.OutmatchBasic;
import com.wyzz.hr.pojo.OutmatchModel;
import com.wyzz.hr.spring.SpringBeanFactory;

import java.util.*;
import org.hibernate.criterion.*;

public class EmpsalarydatadefBoImpl implements IEmpsalarydatadefBo {

	public EmpsalarydatadefBoImpl() {
	}

	public List searchByType(Integer type) {
		if (type == null) {
			return null;
		} else {
			DetachedCriteria detachedCriteria = DetachedCriteria
					.forClass(Empsalarydatadef.class);
			detachedCriteria.add(Restrictions.eq("esddDataType", type));
			return empsalarydatadefDao.findByCriteria(detachedCriteria);
		}
	}

	public Empsalarydatadef searchById(String esddId) {
		if (esddId == null)
			return null;
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.add(Restrictions.eq("esddId", esddId));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		if (list == null || list.size() == 0)
			return null;
		else
			return (Empsalarydatadef) list.get(0);
	}

	public boolean delete(String salaryDataDefId) {
		try {
			String hql = (new StringBuilder()).append(
					"delete from Empsalarydatadef where esddId='").append(
					salaryDataDefId).append("'").toString();
			empsalarydatadefDao.exeHql(hql);
			IOutmatchBasicBO outmatchBasicBO = (IOutmatchBasicBO) SpringBeanFactory
					.getBean("outmatchBasicBO");
			String ombIds = outmatchBasicBO
					.getOmbListByFieldName(salaryDataDefId);
			if (ombIds != null) {
				String deleteOmHql = (new StringBuilder()).append(
						"delete from Outmatch where omOmb.ombId in (").append(
						ombIds).append(")").toString();
				String deleteOmbHql = (new StringBuilder())
						.append(
								"delete from OutmatchBasic where ombFieldName='outPutList.")
						.append(salaryDataDefId).append("'").toString();
				empsalarydatadefDao.exeHql(deleteOmHql);
				empsalarydatadefDao.exeHql(deleteOmbHql);
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean insert(Empsalarydatadef salaryDataDef) {
		salaryDataDef.setEsddSortId(Integer.valueOf(getMaxSortIdEsdd()
				.intValue() + 1));
		empsalarydatadefDao.saveObject(salaryDataDef);
		if (salaryDataDef.getEsddDataOutput().intValue() == 0)
			return true;
		if (10 <= salaryDataDef.getEsddDataType().intValue()
				&& salaryDataDef.getEsddDataType().intValue() <= 16) {
			Boolean result = Boolean.valueOf(insertOmbAndOm("OEmpSalaryPay",
					new Empsalarydatadef[] { salaryDataDef }));
			return result.booleanValue()
					&& insertOmbAndOm("OEmpbenefitHistory",
							new Empsalarydatadef[] { salaryDataDef });
		} else {
			return insertOmbAndOm("OEmpSalaryPay",
					new Empsalarydatadef[] { salaryDataDef });
		}
	}

	public boolean update(Empsalarydatadef salaryDataDef) {
		if ((salaryDataDef.getEsddId() == null)
				|| (salaryDataDef.getEsddId().equals(""))) {
			return false;
		}
		try {
			this.empsalarydatadefDao.updateObject(salaryDataDef);
			IOutmatchBasicBO outmatchBasicBO = (IOutmatchBasicBO) SpringBeanFactory
					.getBean("outmatchBasicBO");
			String ombIds = outmatchBasicBO.getOmbListByFieldName(salaryDataDef
					.getEsddId());
			if (salaryDataDef.getEsddDataOutput().intValue() == 0) {
				if (ombIds == null)
					return true;
				String deleteOmHql = "delete from Outmatch where omOmb.ombId in ("
						+ ombIds + ")";
				String deleteOmbHql = "delete from OutmatchBasic where ombFieldName='outPutList."
						+ salaryDataDef.getEsddId() + "'";
				this.empsalarydatadefDao.exeHql(deleteOmHql);
				this.empsalarydatadefDao.exeHql(deleteOmbHql);
				return true;
			}
			if (ombIds == null) {
				if ((10 <= salaryDataDef.getEsddDataType().intValue())
						&& (salaryDataDef.getEsddDataType().intValue() <= 16)) {
					Boolean result = Boolean.valueOf(insertOmbAndOm(
							"OEmpSalaryPay",
							new Empsalarydatadef[] { salaryDataDef }));
					if (result.booleanValue())
						;
					return insertOmbAndOm("OEmpbenefitHistory",
							new Empsalarydatadef[] { salaryDataDef });
				}
				return insertOmbAndOm("OEmpSalaryPay",
						new Empsalarydatadef[] { salaryDataDef });
			}
			String updateOmHql = "update Outmatch set omFieldDesc='"
					+ salaryDataDef.getEsddName() + "' where omOmb.ombId in ("
					+ ombIds + ")";
			String updateOmbHql = "update OutmatchBasic set ombFieldDesc='"
					+ salaryDataDef.getEsddName()
					+ "' where ombFieldName='outPutList."
					+ salaryDataDef.getEsddId() + "'";
			this.empsalarydatadefDao.exeHql(updateOmHql);
			this.empsalarydatadefDao.exeHql(updateOmbHql);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	public boolean saveSort(String ids[]) {
		if (ids == null)
			return false;
		List esddList = searchEsddByIdArr(ids);
		Map sortIdMap = new HashMap();
		for (int i = 0; i < ids.length; i++) {
			Integer sortId = new Integer(i + 1);
			sortIdMap.put(ids[i], sortId);
		}

		Map fieldSortIdMap = new HashMap();
		Iterator i$ = esddList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Empsalarydatadef esdd = (Empsalarydatadef) i$.next();
			Integer sortId = (Integer) sortIdMap.get(esdd.getEsddId());
			esdd.setEsddSortId(sortId);
			if (esdd.getEsddDataOutput().intValue() == 1)
				fieldSortIdMap.put((new StringBuilder()).append("outPutList.")
						.append(esdd.getEsddId()).toString(), sortId);
		} while (true);
		empsalarydatadefDao.saveOrupdate(esddList);
		Boolean result = Boolean.valueOf(savesortOmbAndOm("OEmpSalaryPay",
				fieldSortIdMap));
		return result.booleanValue()
				&& savesortOmbAndOm("OEmpbenefitHistory", fieldSortIdMap);
	}

	private boolean savesortOmbAndOm(String iodefName, Map fieldSortIdMap) {
		IIodefBo iodefBo = (IIodefBo) SpringBeanFactory.getBean("iodefbo");
		Iodef iodef = iodefBo.searchIodefByName(iodefName);
		if (iodef == null)
			return true;
		String ombFieldNameArr[] = new String[fieldSortIdMap.size()];
		int index = 0;
		for (Iterator i$ = fieldSortIdMap.keySet().iterator(); i$.hasNext();) {
			String dataKey = (String) i$.next();
			ombFieldNameArr[index] = dataKey;
			index++;
		}

		Integer offset = getMaxSortIdOmb(iodef.getIoId(), "outPutList");
		IOutmatchBasicBO outmatchBasicBO = (IOutmatchBasicBO) SpringBeanFactory
				.getBean("outmatchBasicBO");
		List ombList = outmatchBasicBO.getOmbListByFieldNameArr(iodefName,
				ombFieldNameArr);
		OutmatchBasic omb;
		for (Iterator i$ = ombList.iterator(); i$.hasNext(); omb
				.setOmbSortId(Integer.valueOf(((Integer) fieldSortIdMap.get(omb
						.getOmbFieldName())).intValue()
						+ offset.intValue())))
			omb = (OutmatchBasic) i$.next();

		IOutmatchBO outmatchBO = (IOutmatchBO) SpringBeanFactory
				.getBean("outmatchBO");
		List omList = outmatchBO.getOmListByOmbFieldNameArr(ombFieldNameArr);
		Outmatch om;
		for (Iterator i$ = omList.iterator(); i$.hasNext(); om
				.setOmSortId(Integer.valueOf(((Integer) fieldSortIdMap.get(om
						.getOmOmb().getOmbFieldName())).intValue()
						+ offset.intValue())))
			om = (Outmatch) i$.next();

		try {
			empsalarydatadefDao.saveOrupdate(ombList);
			empsalarydatadefDao.saveOrupdate(omList);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean batchRefreshOMConfig() {
		IOutmatchBasicBO outmatchBasicBO = (IOutmatchBasicBO) SpringBeanFactory
				.getBean("outmatchBasicBO");
		String ombIds = outmatchBasicBO.getOmbListByFieldName(null);
		if (ombIds != null) {
			String deleteOmHql = (new StringBuilder()).append(
					"delete from Outmatch where omOmb.ombId in (").append(
					ombIds).append(")").toString();
			String deleteOmbHql = "delete from OutmatchBasic where ombFieldName like 'outPutList.%'";
			empsalarydatadefDao.exeHql(deleteOmHql);
			empsalarydatadefDao.exeHql(deleteOmbHql);
		}
		List esddList = searchAll(Integer.valueOf(1));
		if (esddList.size() == 0)
			return true;
		Boolean result = Boolean.valueOf(insertOmbAndOm("OEmpSalaryPay",
				(Empsalarydatadef[]) esddList
						.toArray(new Empsalarydatadef[esddList.size()])));
		List esddBenefitList = new ArrayList();
		Iterator i$ = esddList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Empsalarydatadef esdd = (Empsalarydatadef) i$.next();
			if (esdd.getEsddDataType().intValue() >= 10
					&& esdd.getEsddDataType().intValue() <= 16)
				esddBenefitList.add(esdd);
		} while (true);
		if (esddBenefitList.size() == 0)
			return true;
		else
			return result.booleanValue()
					&& insertOmbAndOm(
							"OEmpbenefitHistory",
							(Empsalarydatadef[]) esddBenefitList
									.toArray(new Empsalarydatadef[esddBenefitList
											.size()]));
	}

	private boolean insertOmbAndOm(String iodefName,
			Empsalarydatadef esddArray[]) {
		if (esddArray == null || esddArray.length == 0)
			return false;
		IIodefBo iodefBo = (IIodefBo) SpringBeanFactory.getBean("iodefbo");
		Iodef iodef = iodefBo.searchIodefByName(iodefName);
		if (iodef == null)
			return true;
		IOutmatchModelBO outmatchModelBO = (IOutmatchModelBO) SpringBeanFactory
				.getBean("outmatchModelBO");
		List ommList = outmatchModelBO.getListByIodef(iodef);
		Integer offset = getMaxSortIdOmb(iodef.getIoId(), "outPutList");
		List ombList = new ArrayList();
		List omList = new ArrayList();
		Empsalarydatadef arr$[] = esddArray;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			Empsalarydatadef esdd = arr$[i$];
			OutmatchBasic omb = new OutmatchBasic(null, iodef,
					(new StringBuilder()).append("outPutList.").append(
							esdd.getEsddId()).toString(), new Integer(0),
					"decimal", esdd.getEsddName(), Integer.valueOf(esdd
							.getEsddSortId().intValue()
							+ offset.intValue()), new Integer(15));
			omb.setOmbFormat("2");
			ombList.add(omb);
			Outmatch om;
			for (Iterator it = ommList.iterator(); it.hasNext(); omList.add(om)) {
				OutmatchModel omm = (OutmatchModel) it.next();
				om = new Outmatch();
				om.initByOutmatchBasic(omb);
				om.setOmOmm(omm);
			}

		}

		try {
			empsalarydatadefDao.saveOrupdate(ombList);
			if (omList != null && omList.size() != 0)
				empsalarydatadefDao.saveOrupdate(omList);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private List searchAll(Integer esddDataOutput) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.add(Restrictions.eq("esddDataOutput", esddDataOutput));
		detachedCriteria.addOrder(Order.asc("esddSortId"));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		return list;
	}

	private List searchAll(Integer esddDataOutput, Integer typeLow,
			Integer typeHigh) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.add(Restrictions.eq("esddDataOutput", esddDataOutput));
		detachedCriteria.add(Restrictions.ge("esddDataType", typeLow));
		detachedCriteria.add(Restrictions.le("esddDataType", typeHigh));
		detachedCriteria.addOrder(Order.asc("esddSortId"));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		return list;
	}

	public List searchAll() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.addOrder(Order.asc("esddSortId"));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		return list;
	}

	public List findByName(String name) {
		DetachedCriteria dc = DetachedCriteria.forClass(Empsalarydatadef.class);
		dc.add(Restrictions.eq("esddName", name.trim()));
		List list = empsalarydatadefDao.findByCriteria(dc);
		return list;
	}

	public List findSameName(Empsalarydatadef def) {
		DetachedCriteria dc = DetachedCriteria.forClass(Empsalarydatadef.class);
		dc.add(Restrictions.eq("esddName", def.getEsddName().trim()));
		dc.add(Restrictions.ne("esddId", def.getEsddId().trim()));
		List list = empsalarydatadefDao.findByCriteria(dc);
		return list;
	}

	public List findOutput(Integer status) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.add(Restrictions.eq("esddDataOutput", status));
		detachedCriteria.addOrder(Order.asc("esddSortId"));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		return list;
	}

	public List getBenedatadefs() {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.add(Restrictions.eq("esddDataOutput", new Integer(1)));
		detachedCriteria.add(Restrictions.ge("esddDataType", new Integer(10)));
		detachedCriteria.add(Restrictions.le("esddDataType", new Integer(16)));
		detachedCriteria.addOrder(Order.asc("esddSortId"));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		return list;
	}

	public Integer getMaxSortIdEsdd() {
		String hql = "select max(esddSortId) from Empsalarydatadef";
		List list = empsalarydatadefDao.exeHqlList(hql);
		Integer maxID = (Integer) list.get(0);
		return Integer.valueOf(maxID != null ? maxID.intValue() : 1);
	}

	public Integer getMaxSortIdOmb(String ioDefId, String outPutList) {
		String hql = (new StringBuilder())
				.append(
						"select max(ombSortId) from OutmatchBasic where ombIo.ioId = '")
				.append(ioDefId).append("' and ombFieldName not like '")
				.append(outPutList).append(".%'").toString();
		List list = empsalarydatadefDao.exeHqlList(hql);
		Integer intMax = (Integer) list.get(0);
		return Integer.valueOf(intMax != null ? intMax.intValue() : 0);
	}

	public List searchEsddByIdArr(String idArr[]) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empsalarydatadef.class);
		detachedCriteria.add(Restrictions.in("esddId", idArr));
		List list = empsalarydatadefDao.findByCriteria(detachedCriteria);
		return list;
	}

	private String getUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	public IEmpsalarydatadefDao getEmpsalarydatadefDao() {
		return empsalarydatadefDao;
	}

	public void setEmpsalarydatadefDao(IEmpsalarydatadefDao empsalarydatadefDao) {
		this.empsalarydatadefDao = empsalarydatadefDao;
	}

	static final String OSALARYPAY = "OEmpSalaryPay";
	static final String OBENEFITHIS = "OEmpbenefitHistory";
	static final String SALARYIODEFS[] = { "OEmpSalaryPay",
			"OEmpbenefitHistory" };
	IEmpsalarydatadefDao empsalarydatadefDao;

}
